package com.example.docking.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class EncryptionUtil {

    public static String generateAppSignature(String appKey, String appSecret) {
        try {
            // 创建HmacSHA256实例
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKeySpec);

            // 计算HmacSHA256加密结果
            byte[] hmacResult = mac.doFinal(appKey.getBytes(StandardCharsets.UTF_8));

            // 将加密结果转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hmacResult) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            // 将16进制字符串转换为字节数组
            byte[] hexBytes = hexString.toString().getBytes(StandardCharsets.UTF_8);

            // 进行Base64加密
            return Base64.getEncoder().encodeToString(hexBytes);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
    }

//    public static void main(String[] args) {
//        String appKey = "abc";
//        String appSecret = "abc123";
//        String appSignature = generateAppSignature(appKey, appSecret);
//        System.out.println("app_signature = " + appSignature);
//    }
}
